package com.bjpowernode.service.impl;

import com.bjpowernode.entity.TRole;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.mapper.TRoleMapper;
import com.bjpowernode.mapper.TUserMapper;
import com.bjpowernode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    TUserMapper userMapper;

    @Autowired
    TRoleMapper roleMapper;

    /**
     * 该方法是UserDetailsService接口中的抽象方法，该方法会在spring security框架登录的时候调用，
     * 用于根据登录时传过来的用户名加载用户对象的一系列操作
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //根据用户名查询用户对象
        TUser tuser = userMapper.selectByLoginAct(username);
        if(tuser == null){
            throw new UsernameNotFoundException("登录账号不存在");
        }
        //查询该用户对应的角色列表
        List<TRole> roles = roleMapper.selectByUserId(tuser.getId());
        tuser.setTRoleList(roles);
        //我们的TUser已经实现了UserDetails接口，所以可以直接返回tuser
        return tuser;
    }
}
